// simple-logger.ts
import pino from 'pino';
import { join } from 'path';
import { existsSync, mkdirSync } from 'fs';
import dayjs from 'dayjs'

let logger: pino.Logger | null = null;
let currentDate: string = dayjs().format('YYYY-MM-DD');

function getLogFile(): string {
    const logDir = 'logs';
    if (!existsSync(logDir)) {
        mkdirSync(logDir, { recursive: true });
    }
    return join(logDir, `app-${currentDate}.log`);
}

function createLogger() {

    // 使用 pino.transport 配置多目标输出
    const transport = pino.transport({
        targets: [
            {
                level: 'trace',
                target: 'pino/file',
                options: {
                    destination: getLogFile(),
                    mkdir: true
                }
            },
            {
                level: 'trace',
                target: 'pino-pretty', // 控制台输出
                options: {
                    colorize: true,
                    translateTime: 'yyyy-mm-dd HH:MM:ss.l',
                    ignore: 'pid,hostname'
                }
            }
        ]
    });

    return pino(
        {
            level: 'trace',
            timestamp: pino.stdTimeFunctions.isoTime
        },
        transport,
    );
}

function getLogger() {
    // 检查日期是否变更
    const newDate = dayjs().format('YYYY-MM-DD');
    if (newDate !== currentDate) {
        currentDate = newDate;
        logger = createLogger();
    }

    if (!logger) {
        logger = createLogger();
    }

    return logger;
}

// 导出便捷函数
export const infoLog = (obj: any, msg?: string, ...args: any[]) => getLogger().info(obj, msg, ...args);
export const errorLog = (obj: any, msg?: string, ...args: any[]) => getLogger().error(obj, msg, ...args);
export const warnLog = (obj: any, msg?: string, ...args: any[]) => getLogger().warn(obj, msg, ...args);
export const debugLog = (obj: any, msg?: string, ...args: any[]) => getLogger().debug(obj, msg, ...args);
export const fatalLog = (obj: any, msg?: string, ...args: any[]) => getLogger().fatal(obj, msg, ...args);
export const traceLog = (obj: any, msg?: string, ...args: any[]) => getLogger().trace(obj, msg, ...args);